package com.jdym.back.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jdym.R;
import com.jdym.ResponseEnum;
import com.jdym.back.entity.CoBank;
import com.jdym.back.entity.Loan;
import com.jdym.back.entity.Put;
import com.jdym.back.entity.dto.ExcelDTO;
import com.jdym.back.entity.vo.LoanInfo;
import com.jdym.back.service.CoBankService;
import com.jdym.back.service.LoanService;
import com.jdym.back.service.PutService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 贷款表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-09-20
 */
@RestController
@CrossOrigin
@RequestMapping("/back/loan")
public class LoanController {

    @Autowired
    LoanService loanService;
    @Autowired
    CoBankService coBankService;
    @Autowired
    PutService putService;

    @GetMapping("/getCobankFirm/{id}")
    public R getLoanCobankFirm(@PathVariable int id){
        Loan loans = loanService.getLoanCobankFirm(id);
        System.out.println("========"+loans+"===========");
        return R.ok().data("loans",loans).message("连接成功");
    }


//    查询已放款的贷款
    @RequestMapping("/getLoanWithPut")
    public R getLoanWithPut(){

        return R.ok();
    }


//    放款操作
    @RequestMapping(value = "/putMoney/{loanId}")
    public R putMoney(@RequestParam String putMoney,@RequestParam Integer putType,@PathVariable Integer loanId){
        System.out.println("放款钱："+putMoney);
        Put put=new Put();
        put.setPutMoney(putMoney);
        put.setPutType(putType);
        putService.getBaseMapper().insert(put);
        System.out.println("id=====:"+put.getPutId());
        Loan loan=new Loan();
        loan.setLoanId(loanId);
        loan.setPutId(put.getPutId());
        loanService.updateLoanPutId(loan);
        return R.ok();
    }

    @ApiOperation("后台人工办理贷款申请")
    @RequestMapping("/loanApplyBus")
    public R loanApplyBus(@RequestParam Integer loanDeadline,@RequestParam Integer cobankId,@RequestParam BigDecimal loanAmount,@RequestParam String loanPurpose,@RequestParam Integer firmId)
    {
        Loan loan=new Loan();
        loan.setLoanDeadline(loanDeadline);
        loan.setCoBankId(cobankId);
        loan.setLoanAmount(loanAmount);
        loan.setLoanPurpose(loanPurpose);
        loan.setFirmId(firmId);
        loanService.applyLoan(loan);
        int loanid=loan.getLoanId();
        System.out.println("loan:"+loanPurpose+loanDeadline+cobankId+loanAmount+firmId);
        return R.ok().data("loanid",loanid);
    }


    @ApiOperation("获取所有银行")
    @RequestMapping("/getAllCoBand")
    public R getAllCoBand(Model model){
        List<CoBank> coBanks= coBankService.getBaseMapper().selectList(null);
        model.addAttribute("PL","");
       return R.ok().data("coBank",coBanks);

    }

    @ApiOperation("数据的导出")
    @GetMapping("/export/{t}")
    public void export(HttpServletResponse response,@PathVariable int t){
        System.out.println("导出数据");
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("贷款申请数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelDTO.class).sheet("贷款申请").doWrite(loanService.listData(t));

        } catch (IOException e) {
            //EXPORT_DATA_ERROR(104, "数据导出失败"),
            System.out.println("数据导出失败");
        }
    }

//查看所有借款申请
    @GetMapping("/getAllLoanApply")
    public R getAllLoanApply(
            @RequestParam(value = "keyword") String keyWord){

//       List<LoanInfo> loanInfos= loanService.getAllLoanApply();
        List<LoanInfo> loanInfos= loanService.getAllLoanByKeyWord(keyWord);
        return R.ok().data("list",loanInfos);
    }

    @GetMapping("/getAllLoanFileById/{id}")
    public R getAllLoanFileById(@PathVariable int id){
        LoanInfo loanInfo=loanService.getAllLoanFileById(id);
        return R.ok().data("borrowInfoDetail",loanInfo);
    }
//修改贷款状态根据loan的id
    @PutMapping("/updateLoanStutas/{id}")
    public R updateLoanStutas(@PathVariable int id,@RequestParam int status,@RequestParam String advice){
        Loan loan=new Loan();
        loanService.getBaseMapper().update(loan,new UpdateWrapper<Loan>().eq("loan_id",id).set("loan_status",status).set("advice",advice));
        return R.ok();
    }

//    查询所有审批通过的数据
    @GetMapping("/approvedSuc")
    public R approvedSuc(){
        List<LoanInfo> loanInfos= loanService.getAllapprovedSuc();
        return R.ok().data("list",loanInfos);
    }

//    按时间统计贷款的数量
    @GetMapping("/selectStatisics/{start}/{end}")
    public R selectStatisics(@PathVariable String start,@PathVariable String end){
        System.out.println("时间："+start);
//      List<Loan> loans= loanService.getBaseMapper().selectList(new QueryWrapper<Loan>().between("createTime",start,end));
        List<Loan> loans=  loanService.selectStatisics(start,end);
      return R.ok().data("loans",loans);
    }
}

